/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2009, Around(J2)ME				                                 **
 **   All rights reserved.                                                   **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the New BSD License which accompanies this    			 **
 **   distribution.											                 **
 **   A copy is found in the textfile LICENSE.txt							 **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Main developers:                                                       **
 **     Juri Strumpflohner		http://blog.js-development.com	             **
 **		Matthias Braunhofer		http://matthias.jimdo.com                    **
 **                                                                          **
 **  **********************************************************************  */

package org.aroundme.unittests;

import java.io.IOException;
import java.util.ArrayList;

import org.aroundme.controller.HttpController;
import org.aroundme.model.CategoryName;
import org.aroundme.model.Location;
import org.aroundme.model.Place;
import org.aroundme.model.XMLRequestParser;
import org.aroundme.persistency.LocationManager;
import org.aroundme.unitTools.TestFixture;
import org.aroundme.unitTools.UniqueIdGenerator;
import org.aroundme.utility.Constants;
import org.aroundme.utility.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.jdom.JDOMException;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

public class HttpControllerTest extends TestFixture {
	private HttpController httpController;
	private XMLRequestParser requestParser;
	private LocationManager locManager;
	
	protected void setUp() throws Exception {
		super.setUp();
		httpController = (HttpController) springFactory.getBean(HttpController.class.getSimpleName());
		requestParser = (XMLRequestParser) springFactory.getBean(XMLRequestParser.class.getSimpleName());
		locManager = (LocationManager) springFactory.getBean(LocationManager.class.getSimpleName());
	}

	protected void tearDown() throws Exception {
		super.tearDown();
		httpController = null;
		requestParser = null;
		locManager = null;
	}

	/**
	 * Acceptance test that if requests are send, they are successfully stored
	 * in the DB after passing all the internal processing
	 * @throws IOException
	 * @throws JDOMException 
	 */
	public void testHandlePlaceCommitRequest() throws IOException, JDOMException {
//		Creating Mock objects
		MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", "/");
		MockHttpServletResponse mockResponse = new MockHttpServletResponse();
		mockRequest.setContentType("application/octet-stream");
		
		//create necessary users
		xmlTestUtils.saveDummyUsersToDB();
		
		//creating dummy xml-file
		String xmlFile = xmlTestUtils.createXMLCommitString(Constants.COMMIT_PLACE, "variable", new String[]{CategoryName.HOTELS.toString(), CategoryName.BARS.toString()});
		mockRequest.setContent(xmlFile.getBytes());
		
		//initialize xmlRequest parser since this would be done normally by the HttpRequestInterceptor
		requestParser.loadDocumentModel(xmlFile);
		
		assertNotNull(httpController);
		httpController.handleRequest(mockRequest, mockResponse);
		
		//if the items have been processed correctly they should be in the DB now -> check
		//retrieve stored places
		Session s = HibernateUtil.getSessionFactory().getCurrentSession();
		Place place1 = null;
		Place place2 = null;
		Place place3 = null;
		s.beginTransaction();
		try{
			place1 = (Place) s.createQuery("from Place where name=?").setString(0, xmlTestUtils.getDummyPlaces().get(0).getName()).uniqueResult();
			place2 = (Place) s.createQuery("from Place where name=?").setString(0, xmlTestUtils.getDummyPlaces().get(1).getName()).uniqueResult();
			place3 = (Place) s.createQuery("from Place where name=?").setString(0, xmlTestUtils.getDummyPlaces().get(2).getName()).uniqueResult();
			s.getTransaction().commit();
		}catch (HibernateException e){
			s.getTransaction().rollback();
			throw e;
		}
		assertNotNull(place1);
		assertNotNull(place2);
		assertNotNull(place3);
		
		assertEquals("Name", xmlTestUtils.getDummyPlaces().get(0).getName(), place1.getName());
		assertEquals("Name", xmlTestUtils.getDummyPlaces().get(1).getName(), place2.getName());
		assertEquals("Name", xmlTestUtils.getDummyPlaces().get(2).getName(), place3.getName());
		assertEquals("Address", xmlTestUtils.getDummyPlaces().get(0).getAddress(), place1.getAddress());
		assertEquals("Address", xmlTestUtils.getDummyPlaces().get(1).getAddress(), place2.getAddress());
		assertEquals("Address", xmlTestUtils.getDummyPlaces().get(2).getAddress(), place3.getAddress());
		assertEquals("user", xmlTestUtils.getDummyPlaces().get(0).getUser().getLoginName(), place1.getUser().getLoginName());
		assertEquals("user", xmlTestUtils.getDummyPlaces().get(1).getUser().getLoginName(), place2.getUser().getLoginName());
		assertEquals("user", xmlTestUtils.getDummyPlaces().get(2).getUser().getLoginName(), place3.getUser().getLoginName());
	}
	
	/**
	 * Acceptance test: Sends a dummy xml request to the server and checks if the returned places are the
	 * requested ones
	 * @throws IOException
	 * @throws JDOMException 
	 */
	public void testHandlePlaceRetrieveRequestAll() throws IOException, JDOMException{
		//Creating Mock objects
		MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", "/");
		MockHttpServletResponse mockResponse = new MockHttpServletResponse();
		mockRequest.setContentType("application/octet-stream");
		
//		create necessary users
		xmlTestUtils.saveDummyUsersToDB();
		
		//store dummy places into the DB in s.t. they can be retrieved by the test
		Location loc = new Location();
		loc.setCellid("" + new UniqueIdGenerator().getUniqueId());
		loc.setLat("somelat");
		loc.setLon("someLong");
		ArrayList<Place> places = xmlTestUtils.getDummyPlaces();
		for (Place place : places) {
			loc.addPlace(place);
		}
		
		locManager.saveLocation(loc);
		
		
		//creating dummy xml-file
		String xmlFile = xmlTestUtils.createXMLRetrieveString(Constants.RETRIEVE_PLACE, Constants.PARAM_RETRIEVE_ALL, null, null, 0, 9999999);
		mockRequest.setContent(xmlFile.getBytes());
		
//		initialize xmlRequest parser since this would be done normally by the HttpRequestInterceptor
		requestParser.loadDocumentModel(xmlFile);
		
		assertNotNull(httpController);
		httpController.handleRequest(mockRequest, mockResponse);
		
		String xmlString = mockResponse.getContentAsString();
		
		assertNotNull(xmlString);
				
		
		for (Place place : places) {
			assertTrue("Id of place", xmlString.contains("<id>" + place.getId() + "</id>"));
			assertTrue("Name of place", xmlString.contains("<name>" + place.getName() + "</name>"));
			assertTrue("Address of place", xmlString.contains("<address>" + place.getAddress() + "</address>"));
			assertTrue("User of place", xmlString.contains("<user>" + place.getUser().getLoginName() + "</user>"));
		}
	}
}
